#include "shelf.h"

#include <QVector>

Shelf::Shelf(int capacity, QObject *parent) :
    QObject(parent)
{
    capacity_ = capacity;
}

int Shelf::tryToPlaceBook()
{
    placingMutex_.lock();
    if(books_.size() > capacity_) {
        placingMutex_.unlock();
        return -1;
    }

    int position = books_.size();
    books_.push_back(0);
    mutexes_.push_back(new QMutex);
    emit wrotedBook();
    placingMutex_.unlock();
    return position;
}

void Shelf::takeForEdit(int position) {
    emit waitForEdit();
    mutexes_.at(position)->lock();
}

void Shelf::returnFromEdit(int position) {
    mutexes_.at(position)->unlock();
    emit doneEdit();
}

void Shelf::returnBook(int position) {
    mutexes_.at(position)->unlock();
}

bool Shelf::takeForReading(int position) {
    return mutexes_.at(position)->tryLock();
}

size_t Shelf::size()
{
    return books_.size();
}
